package cn.lili.config;

import cn.lili.util.TemplateHtml;
import cn.lili.util.TemplateMessage;
import cn.wildfirechat.pojos.SendChannelMessageData;
import cn.wildfirechat.sdk.AdminConfig;
import cn.wildfirechat.sdk.ChannelServiceApi;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Configuration
@RefreshScope
@Slf4j
public class ImConfig {

    @Value("${fw.im_url}")
    String imUrl;

    @Value("${fw.im_secret}")
    String secret;


    @Bean
    public ChannelServiceApi channel() throws Exception {
        log.info("channel init url:{}", imUrl);
        // 商城通知频道
        return new ChannelServiceApi(imUrl, "shop_fy_d78sad8378bn6", "shop_dsahu#sadsaKsie9217");
    }

    public static void main(String[] args) throws Exception {
        AdminConfig.initAdmin("http://fy.chainlettre05.com:30080", "wendi666qwertghjkldsa");
        Gson gson = (new GsonBuilder()).disableHtmlEscaping().create();
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setValidateAfterInactivity(1000);
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).evictExpiredConnections().evictIdleConnections(60L, TimeUnit.SECONDS).setRetryHandler(DefaultHttpRequestRetryHandler.INSTANCE).setMaxConnTotal(100).setMaxConnPerRoute(50).build();

        List<String> targets = new ArrayList<>();
        targets.add("1737724076924026881");

        TemplateMessage message = TemplateHtml.sendMessageForHtml("飞语会议返商城余额", "3.5", "123456", "飞语会议返现", "1", 1);
        SendChannelMessageData messageData = new SendChannelMessageData();
        messageData.setLine(0);
        messageData.setTargets(targets);
        messageData.setPayload(message);
        String path = "/channel/message/send";
        int nonce = (int)(Math.random() * 100000.0 + 3.0);
        long timestamp = System.currentTimeMillis();
        String str = nonce + "|" + "shop_dsahu#sadsaKsie9217" + "|" + timestamp;
        String sign = DigestUtils.sha1Hex(str);
        HttpPost post = new HttpPost("http://fy.chainlettre05.com:30080" + path);
        post.setHeader("Content-type", "application/json; charset=utf-8");
        post.setHeader("Connection", "Keep-Alive");
        post.setHeader("nonce", nonce + "");
        post.setHeader("timestamp", "" + timestamp);
        post.setHeader("cid", "shop_fy_d78sad8378bn6");
        post.setHeader("sign", sign);
        String jsonStr = "";
        jsonStr = gson.toJson(messageData);

        StringEntity entity = new StringEntity(jsonStr, Charset.forName("UTF-8"));
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        post.setEntity(entity);
        HttpResponse response = httpClient.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println(statusCode);
        /*InputCreateChannel atCreateChannel = new InputCreateChannel();
        atCreateChannel.setName("商城通知");
        atCreateChannel.setOwner("1");
        String secret = "shop_dsahu#sadsaKsie9217";
        String channelId = "shop_fy_d78sad8378bn6";
        atCreateChannel.setSecret(secret);
        atCreateChannel.setTargetId(channelId);
        atCreateChannel.setAuto(1);
        atCreateChannel.setDesc("商城通知");
        atCreateChannel.setPortrait("https://feiyu-shop-pic.oss-cn-beijing.aliyuncs.com/shop/shopNotify.png");
        atCreateChannel.setState(Channel_State_Mask_FullInfo | Channel_State_Mask_Unsubscribed_User_Access | Channel_State_Mask_Active_Subscribe | Channel_State_Mask_Message_Unsubscribed);
        IMResult<OutputCreateChannel> resultCreateChannel4 = GeneralAdmin.createChannel(atCreateChannel);
        if (resultCreateChannel4 != null && resultCreateChannel4.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
            System.out.println("商城通知频道创建成功");
        } else {
            System.out.println(resultCreateChannel4.getErrorCode() + ":" + resultCreateChannel4.getMsg());
        }*/
    }
}
